<?php

namespace App\Http\Controllers\Common;

use App\Http\Controllers\Controller;
use App\Models\Module;
use App\Services\PayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Yansongda\Pay\Pay;

class PayController extends Controller
{
    public function __construct()
    {
        //实例化时先执行中间件
        $this->middleware('front');
    }

    //
    public function alipaySync(Module $module, PayService $payService)
    {


        $data = Pay::alipay($payService->alipayConfig())->verify()->toArray();

        //根据模块构建对应的类，然后不同模块根据自身需求处理通知verify
        //有点像父类和子类的关系
        return $this->moduleNotify($module, $data);

    }

    public function alipayAsync(Module $module, PayService $payService)
    {
//        Log::info(Route::currentRouteAction());

        $alipay = Pay::alipay($payService->alipayConfig());

        $data = $alipay->verify();

//        Log::info($data);
        $this->moduleNotify($module, $data);
        //异步通知,支付宝出现情况后，出现异常会启动异步，不定时发送通知，直至返回success
        return $alipay->success();
    }

    public function wepayAsync(Module $module, PayService $payService)
    {
        $wepay = Pay::wechat($payService->wepayConfig());
        $data = $wepay->verify();

        $this->moduleNotify($module, $data);
        return $wepay->success();
    }

    //通知模块改变订单状态
    public function moduleNotify($data, $module)
    {
        $data['sn'] = $data['out_trade_no'];
        $class = 'Modules\\' . $module['name'] . '\System\Pay';
        return app($class)->notify($data);

    }
}
